package com.tang.init;

import com.tang.server.NettyServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * 开机启动netty
 *
 * @author fulin.tang
 * @version V3.0
 * @since 2022/5/18 16:13
 */
@Component
public class NettyInit implements CommandLineRunner {

    @Value("${netty.host}")
    private String host;

    @Value("${netty.port}")
    private int port;

    private final NettyServer nettyServer;

    public NettyInit(NettyServer nettyServer) {
        this.nettyServer = nettyServer;
    }

    @Override
    public void run(String... args) {
        InetSocketAddress address = new InetSocketAddress(host, port);
        ChannelFuture channelFuture = nettyServer.bing(address);
        Runtime.getRuntime().addShutdownHook(new Thread(nettyServer::destroy));
        channelFuture.channel().closeFuture().syncUninterruptibly();
    }

}
